package com.smit.adapter;

import android.content.Context;
import android.os.Build;

import com.smit.common.AppData;
import com.smit.common.AuthControl;
import com.smit.dvb.DVBManager;
import com.smit.icast.ICastDVBManager;
import com.smit.icastplus.ICastPlusDVBManager;
import com.smit.utils.LogUtil;
import com.smit.utils.StrUtil;

/**
 * DVBAdapter 用来统一管理DVB服务、DVB设备和DVB数据
 */
public final class DVBAdapter {
    private static final String TAG = "DVBAdapter";
    private Context context;
    private int dvbDeviceType = 0;
    private DVBManager dvbManager;
    private DVBDeviceManager dvbDeviceManager;
    private DVBDataManager dvbDataManager;
    private boolean bSDKInitializeOk = false;

    private DVBAdapter() {
        printSdkInfo();
    }


    /**
     * 获取DVBAdapter实例
     *
     * @return DVBAdapter单例
     */
    public static DVBAdapter getInstance() {
        return SingletonHolder.instance;
    }

    /**
     * 初始化icast，包括DVB设备管理和DVB服务
     *
     * @param context Android Application Context
     * @param appID 分配给合作开发的应用ID
     * @param appKey 分配给合作开发的应用Key
     */
    public void initialize(Context context, String appID, String appKey) {
        LogUtil.info(TAG, "initialize start>>>");

        if (context == null) {
            throw new IllegalArgumentException("context is null when initialize iCast SDK!!");
        }
        this.context = context;

        // 检查appID 和 appKey
        if (bSDKInitializeOk) {
            LogUtil.info(TAG, "iCast SDK has initialized");
            printSdkInfo();
            return;
        }
        if (!checkIdAndKey(appID, appKey)) {
            LogUtil.info(TAG, "appID and appKey are not valid!");
            return;
        }

        // 加载dvb lib
        dvbDataManager = new DVBDataManager(context);
        loadNativeLibs(dvbDataManager);

        // 初始化dvb manager
        dvbDeviceManager = new DVBDeviceManager(context);
        dvbDeviceType = dvbDeviceManager.getDeviceType();
        LogUtil.info(TAG, "initialize dvbDeviceType=" + dvbDeviceType);
        switch (dvbDeviceType) {
            case DVBDeviceManager.DVB_DEVICE_ICAST:
                dvbManager = new ICastDVBManager(context);
                dvbManager.initialize();
                break;
            case DVBDeviceManager.DVB_DEVICE_ICAST_PLUS:
                dvbManager = new ICastPlusDVBManager(context);
                dvbManager.initialize();
            default: // 默认启动icast
                dvbManager = new ICastDVBManager(context);
                dvbManager.initialize();
                break;
        }
        // 加载频点表
        dvbDataManager.loadFreqTable(false, null);
        // 初始化 AuthControl
        AuthControl.getInstance().initialize(context);
        AuthControl.getInstance().setAppId(appID);
        AuthControl.getInstance().setAppKey(appKey);
        // 启动鉴权
        AuthControl.getInstance().startAuth();
        // SDK 初始化成功
        bSDKInitializeOk = true;
        LogUtil.info(TAG, "initialize end<<<");
    }

    /**
     * 释放资源
     */
    public void release() {
        // 停止鉴权
        AuthControl.getInstance().stopAuth();
        if (dvbManager != null) {
            dvbManager.release();
        }
        if (dvbDeviceManager != null) {
            dvbDeviceManager = null;
        }
        dvbDeviceType = 0;
    }

    /**
     * 获取DVB服务管理
     *
     * @return DVBManager对象
     */
    public DVBManager getDVBManager() {
        return dvbManager;
    }

    /**
     * 获取DVB设备管理
     *
     * @return DVBDeviceManager对象
     */
    public DVBDeviceManager getDVBDeviceManager() {
        return dvbDeviceManager;
    }

    /**
     * 获取 DVB 插件管理
     * @return DVB插件管理器
     */
    public DVBDataManager getDVBDataManager() {
        return dvbDataManager;
    }

    private void printSdkInfo() {
        LogUtil.info(TAG, "iCast SDK_VERSION_NAME=" + AppData.SDK_VERSION_NAME);
        LogUtil.info(TAG, "iCast SDK_VERSION_CODE=" + AppData.SDK_VERSION_CODE);
        LogUtil.info(TAG, "iCast SDK_API_LEVEL=" + AppData.SDK_API_LEVEL);
        LogUtil.info(TAG, "iCast SDK_API_REVISION=" + AppData.SDK_API_REVISION);
    }
    /**
     * 检查appID appKey是否合法
     * @param appID 分配给合作开发的应用ID
     * @param appKey 分配给合作开发的应用Key
     * @return true 合法，false 不合法
     */
    private boolean checkIdAndKey(String appID, String appKey) {
        LogUtil.info(TAG, "checkIdAndKey start>>>");
        if (StrUtil.isNullOrEmpty(appKey)) {
            throw new IllegalArgumentException("appKey is null or empty!!");
        }
        if (StrUtil.isNullOrEmpty(appID)) {
            throw new IllegalArgumentException("appID is null or empty!!");
        }

        if (AppData.getKeyMap().containsKey(appID) && appKey.equals(AppData.getKeyMap().get(appID))) {
                LogUtil.info(TAG, "checkIdAndKey appID and appKey are valid");
                LogUtil.info(TAG, "checkIdAndKey end<<<");
                return true;
        }
        LogUtil.info(TAG, "checkIdAndKey end<<<");
        return false;
    }

    /**
     * 加载Native libs，有DVB基础库，DVB插件库等
     *
     * @param manager DVBDataManager
     */
    private void loadNativeLibs(DVBDataManager manager) {
        if (manager == null) {
            throw new IllegalArgumentException("Data error for native libs!!");
        }
        if (Build.CPU_ABI.contains("armeabi") || Build.CPU_ABI.contains("arm64-v8a")) {
            LogUtil.debug(TAG, "CPU  type is " + Build.CPU_ABI);
            manager.loadBaseLib();
            manager.updateAllData();
        } else {
            LogUtil.error(TAG, "CPU is not armeabi or arm64-v8a,native libs is incompatible");
            throw new IllegalArgumentException("CPU is not armeabi or arm64-v8a,native libs is incompatible!!");
            //System.exit(0);
        }
    }

    private static class SingletonHolder {
        private static DVBAdapter instance = new DVBAdapter();
    }
}